package com.example.communicate;

import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.ArrayList;

public class MessageBroadcast {
    private List<ClientHandler> clients;

    // 构造方法，初始化客户端处理器列表
    public MessageBroadcast() {
        clients = new ArrayList<>();
    }

    // 注册客户端处理器
    public void registerClient(ClientHandler clientHandler) {
        clients.add(clientHandler);
        System.out.println("客户端已注册：" + clientHandler);
    }

    // 向所有客户端广播消息
    public void broadcastMessage(String message) {
        for (ClientHandler client : clients) {
            client.sendMessage(message);
        }
        System.out.println("广播消息：" + message);
    }

    // 内部类，用于处理客户端连接
    public static class ClientHandler {
        private Socket clientSocket;

        public ClientHandler(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        // 发送消息到客户端
        public void sendMessage(String message) {
            try {
                clientSocket.getOutputStream().write(message.getBytes());
                System.out.println("向客户端发送消息：" + message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
